package ui;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.hardware.bcreader.BCRBarCodeValue;
import android.hardware.bcreader.BCRListener;
import android.hardware.bcreader.BCRManager;
import android.hardware.bcreader.BCRTicketInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sxpjyy.monkey.mobilenurse.R;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import adapters.PatientsListAdapter;
import mytools.MyBaseActivity;
import objects.InPatient;
import objects.InPatient_BRBS;
import objects.Section;
import service.WebService;

public class PatientsListActivity extends MyBaseActivity implements SwipeRefreshLayout.OnRefreshListener, ListView.OnItemClickListener {

    private ListView listView;
    private List<InPatient> mInPatientList;
    private PatientsListAdapter patientsAdapter;

    private TextView sectionName;

    private static ProgressDialog progressDialog = null;

    private String BRBQ = null;
    private String mInpatientResult = null;

    private SwipeRefreshLayout swipeRefreshLayout;

    private MyHandler handler;

    private BCRManager mBCRManager;
    private BCRTicketInfo mBCRTicketInfo[] = {null, null};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_patients_list);
        onBindUI();

        handler = new MyHandler(this);

        patientsAdapter = new PatientsListAdapter(this);
        listView.setAdapter(patientsAdapter);
        listView.setOnItemClickListener(this);

        swipeRefreshLayout.setColorSchemeResources(R.color.holo_green_dark, R.color.holo_green_light, R.color.holo_orange_light, R.color.holo_red_light);
        swipeRefreshLayout.setOnRefreshListener(this);

        BCRListener mListener = new MyListener();
        mBCRManager = BCRManager.getInstance();
        mBCRManager.registerListener(mListener);
    }

    @Override
    protected void onResume() {
        super.onResume();
        Section section = getMyApplication().getSection();
        if (section != null) {
            sectionName.setText(section.getKSMC());
            BRBQ = section.getKSDM();
            showProgressBar(this);
            new MyPatientTask().execute();
        } else {
            Toast.makeText(this, "获取病区数据失败，请重新登陆！", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(this, LoginActivity.class));
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        mBCRManager.stopScan();
    }

    @Override
    protected void onStop() {
        super.onStop();
        mBCRManager.stopScan();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mBCRManager.isReady()) {
            mBCRManager.close();
        }
    }

    @Override
    public void onBackPressed() {
        finish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case 1300:
            case 1301:
                if (mInPatientList == null || mInPatientList.size() < 1) {
                    Toast.makeText(PatientsListActivity.this, "该病区无病人！", Toast.LENGTH_SHORT).show();
                } else {
                    mBCRManager.open(this);
                }
                break;
            default:
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onRefresh() {
        new MyPatientTask().execute();
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        switch (adapterView.getId()) {
            case R.id.patients_list:
                InPatient inPatient = mInPatientList.get(i);
                if (inPatient != null) {
                    Intent intent = new Intent(PatientsListActivity.this, PatientDetailActivity.class);
                    Bundle bundle = new Bundle();
                    getMyApplication().setInPatient(inPatient);
                    intent.putExtras(bundle);
                    startActivity(intent);
                }
                break;
            default:
                break;
        }
    }

    private static class MyHandler extends Handler {

        WeakReference<PatientsListActivity> mActivity;

        MyHandler(PatientsListActivity activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            PatientsListActivity activity = mActivity.get();
            switch (msg.what) {
                case 0x11:
                    activity.mBCRManager.stopScan();
                    activity.new MyPatientBRBSTask().execute(activity.mBCRTicketInfo[0].getTicketValue());
                    break;
                case 0x99:
                    activity.mBCRManager.stopScan();
                    Toast.makeText(activity, "扫描数据错误！", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    }

    private void onBindUI() {
        listView = findViewById(R.id.patients_list);
        sectionName = findViewById(R.id.which_area);
        swipeRefreshLayout = findViewById(R.id.patient_swipe_ly);
    }

    //显示进度对话框
    private static void showProgressBar(Context context) {
        progressDialog = new ProgressDialog(context);
        progressDialog.setMessage("正在获取信息。。。");
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    //取消进度对话框
    private static void cancelProgressBar() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.cancel();
            progressDialog = null;
        }
    }

    /**
     * 获取病人列表操作
     */
    private class MyPatientTask extends AsyncTask<Void, Void, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            listView.setEnabled(false);
        }

        @Override
        protected String doInBackground(Void... voids) {
            WebService inpatientWebService = new WebService(PatientsListActivity.this);
            inpatientWebService.setMETHOD_NAME("getPatientsList");
            if (BRBQ.equals("")) {
                return "病区为空！";
            } else {
                String result;
                String[] Parms = {BRBQ};
                inpatientWebService.setPARMS(Parms);
                result = inpatientWebService.getServerData();
                if (result == null || result.equals("null") || result.equals("") || result.equals("[]")) {
                    return "获取住院病人列表为空！";
                } else {
                    if (!result.equals(mInpatientResult)) {
                        mInpatientResult = result;
                        Gson gson = new Gson();
                        mInPatientList = gson.fromJson(mInpatientResult, new TypeToken<List<InPatient>>() {
                        }.getType());
                        if (mInPatientList != null && mInPatientList.size() > 0) {
                            //按床位号排序
                            Collections.sort(mInPatientList, (arg0, arg1) -> arg0.getBRCH().compareTo(arg1.getBRCH()));
                            return null;
                        } else {
                            return "获取住院病人列表失败!";
                        }
                    } else {
                        return "数据未发生变化";
                    }
                }
            }
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            cancelProgressBar();
            if (swipeRefreshLayout.isRefreshing()) {
                swipeRefreshLayout.setRefreshing(false);
            }
            listView.setEnabled(true);
            if (s != null) {
                Toast.makeText(PatientsListActivity.this, s, Toast.LENGTH_SHORT).show();
            } else {
                patientsAdapter.setList(mInPatientList);
                patientsAdapter.notifyDataSetChanged();
            }
        }
    }

    /**
     * 扫码监听
     */
    private class MyListener implements BCRListener {
        @Override
        public void onScanFinished(int scanType, String elapseTime) {
            mBCRTicketInfo = mBCRManager.getTicketInfo();
            Message msg = new Message();
            if (mBCRTicketInfo != null) {
                msg.what = 0x11;
            } else {
                msg.what = 0x99;
            }
            handler.sendMessage(msg);
        }

        @Override
        public void onOpened(boolean isReady) {
            if (isReady) {
                mBCRManager.enableCode(BCRBarCodeValue.CODE_TYPE_DATA_MATRIX);
                mBCRManager.enableCode(BCRBarCodeValue.CODE_TYPE_INTERLEAVED_2_OF_5);
                mBCRManager.enableCode(BCRBarCodeValue.CODE_TYPE_PDF417);
                mBCRManager.startScan(BCRManager.SCAN_TYPE_SINGLE, BCRManager.SCAN_MODE_CONTINUE);
            }
        }
    }

    /**
     * 获取病人标识操作
     */
    private class MyPatientBRBSTask extends AsyncTask<String, Void, String> {

        private List<InPatient_BRBS> list;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            list = new ArrayList<>();
            showProgressBar(PatientsListActivity.this);
        }

        @Override
        protected String doInBackground(String... strings) {
            WebService brbsWebService = new WebService(PatientsListActivity.this);
            brbsWebService.setMETHOD_NAME("getPatientBrbs");
            brbsWebService.setPARMS(strings);
            String result = brbsWebService.getServerData();
            if (result == null || result.equals("null") || result.equals("") || result.equals("[]")) {
                return "获取病人标识为空！";
            } else {
                Gson gson = new Gson();
                list = gson.fromJson(result, new TypeToken<List<InPatient_BRBS>>() {
                }.getType());
                if (mInPatientList != null && mInPatientList.size() > 0) {
                    return null;
                } else {
                    return "获取病人标识失败!";
                }
            }
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            cancelProgressBar();
            if (s != null && !s.equals("")) {
                Toast.makeText(PatientsListActivity.this, s, Toast.LENGTH_SHORT).show();
            } else {
                String ZYH = list.get(0).getZYH();
                int position = 0;
                boolean isfound = false;
                for (InPatient inPatient : mInPatientList
                        ) {
                    if (inPatient.getZYH().equals(ZYH)) {
                        isfound = true;
                        break;
                    }
                    position++;
                }
                if (!isfound) {
                    Toast.makeText(PatientsListActivity.this, "该病区不存在该病人！", Toast.LENGTH_SHORT).show();
                } else {
                    listView.performItemClick(listView.getChildAt(position), position, listView.getItemIdAtPosition(position));
                }
            }

        }
    }
}
